#!/bin/bash

# Provide source directive to shellcheck.
# shellcheck source=meta-facebook/meta-greatlakes/recipes-phosphor/state/phosphor-state-manager/power-cmd
source /usr/libexec/phosphor-state-manager/power-cmd

HOST_ID=$1
SLOT_ID=$(( $1-1  << 2 ))

# Host Reboot
host-reboot()
{
        power_delay=$1
        for pwr_cmd in "${power_seq[@]}"
        do
             response="$(busctl call "$SERVICE" "$OBJECT_PATH" "$INTERFACE" sendRequest yyyyay "$SLOT_ID" "$NETFN" "$LUN" "$CMD" "$DATA_LEN" 0x01 0x42 0x01 0x00 "$pwr_cmd")"
             echo "$response"
             result=$(echo "$response" | cut -d" " -f "$IPMB_CMD_COMPLETE_CODE_INDEX")
             if [ "$result" -ne 0 ]
             then
                     echo "Failed to send ipmb command"
                     exit 1
             fi
             if [ "$pwr_cmd" == "$POWER_BTN_LOW" ]
             then
                     sleep "$power_delay"
             fi
        done
}

# Check Host Response and Status
host_status=$(host-power-status $SLOT_ID)
if [ "$host_status" == "$STATE_ON" ]
then
  host-reboot 6
  sleep 15
  host-reboot 2

  host_status=$(host-power-status $SLOT_ID)
  if [ "$host_status" == "$STATE_ON" ]
  then
      busctl set-property "$HOST_BUS_NAME""$HOST_ID" "$HOST_OBJ_PATH""$HOST_ID" "$HOST_INTF_NAME" "$HOST_PROPERTY_NAME" s "$HOST_ON"
      exit 0;
  else
      busctl set-property "$HOST_BUS_NAME""$HOST_ID" "$HOST_OBJ_PATH""$HOST_ID" "$HOST_INTF_NAME" "$HOST_PROPERTY_NAME" s "$HOST_OFF"
      exit 0;
  fi
else
  echo "Host is Off"
  exit 1;
fi
